package com.zzyl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MemberServiceImpl implements MemberService {


    @Autowired
    private WechatService wechatService;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        // 1、根据code获取openId
        String openid = wechatService.getOpenid(dto.getCode());

        // 2、根据openid判断客户是否为空
        Member member = memberMapper.findByOpenid(openid);


        // 3、根据phoneCode重新获取手机号
        String phone = wechatService.getPhone(dto.getPhoneCode());

        // 4、新增或修改手机号
        // //如果为空，直接创建
        if(member==null){
            member = Member.builder()
                    .openId(openid)
                    .name(dto.getNickName())
                    .phone(phone)
                    .build();
            memberMapper.add(member);
        }else{  // member不为空 看是否需要修改手机号
            if(!StrUtil.equals(member.getPhone(),phone)){
                member.setPhone(phone);
                memberMapper.update(member);
            }

        }

        // 5、生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());

        String token =  JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),jwtTokenManagerProperties.getTtl(),claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(member.getName());

        return loginVo;
    }
}
